<template>
  <div class="powerbi-designer">
    <!-- 顶部工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <h2>PowerBI 设计器</h2>

        <!-- Vue3 Grid Layout 控制 -->
        <el-divider direction="vertical" />
        <span class="toolbar-label">列数:</span>
        <el-input-number v-model="colNum" :min="6" :max="24" size="small" style="width: 80px;" />

        <span class="toolbar-label">行高:</span>
        <el-input-number v-model="rowHeight" :min="30" :max="100" size="small" style="width: 80px;" />

        <el-switch v-model="isDraggable" size="small" active-text="可拖拽" inactive-text="锁定" />
        <el-switch v-model="isResizable" size="small" active-text="可调整" inactive-text="固定" />

        <el-button size="small" @click="initializeLayout" :disabled="!visualizations.length">
          <el-icon><Operation /></el-icon>
          重新布局
        </el-button>
      </div>
      <div class="toolbar-right">
        <el-button @click="showImportDialog = true">
          <el-icon><Upload /></el-icon>
          导入数据
        </el-button>
        <el-button @click="goToDataModel">
          <el-icon><Connection /></el-icon>
          数据模型
        </el-button>
        <el-button @click="showReportManager = true">
          <el-icon><Folder /></el-icon>
          报表管理
        </el-button>
        <el-button type="primary" @click="saveReport">保存报表</el-button>
        <el-button @click="previewReport">预览</el-button>
        <el-button @click="showExportDialog = true">
          <el-icon><Download /></el-icon>
          导出
        </el-button>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧面板 -->
      <div class="left-panel">
        <div class="panel-tabs">
          <el-tabs v-model="activeTab" type="border-card">
            <el-tab-pane label="字段" name="fields">
              <FieldPanel />
            </el-tab-pane>
            <el-tab-pane label="筛选器" name="filters">
              <FilterPanel />
            </el-tab-pane>
            <el-tab-pane label="主题" name="theme">
              <ThemeSelector />
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>

      <!-- 中间设计区域 -->
      <div class="design-area">
        <div
          class="design-canvas"
          :class="{
            'grid-mode': layoutMode === 'grid',
            'show-grid': showGrid && layoutMode === 'free',
            'snap-enabled': snapToGrid
          }"
          :style="layoutMode === 'grid' ? gridContainerStyle : canvasStyle"
          @drop="onDrop"
          @dragover.prevent
          @dragenter.prevent">

          <!-- 网格背景 -->
          <div v-if="showGrid && layoutMode === 'free'" class="grid-background" :style="gridBackgroundStyle"></div>

          <!-- Flex拖拽插入指示器 -->
          <div v-if="dropIndicator && dropIndicator.visible"
               class="drop-indicator"
               :style="{
                 position: 'absolute',
                 top: dropIndicator.y + 'px',
                 left: '0',
                 right: '0',
                 height: '3px',
                 background: '#409EFF',
                 borderRadius: '2px',
                 zIndex: 1000,
                 boxShadow: '0 0 8px rgba(64, 158, 255, 0.5)'
               }">
          </div>

          <!-- Vue3 Grid Layout -->
          <GridLayout
            v-model:layout="layout"
            :col-num="colNum"
            :row-height="rowHeight"
            :is-draggable="isDraggable"
            :is-resizable="isResizable"
            :is-mirrored="isMirrored"
            :vertical-compact="verticalCompact"
            :margin="margin"
            :use-css-transforms="useCssTransforms"
            @layout-updated="onLayoutUpdated"
            :style="gridContainerStyle">

            <GridItem
              v-for="item in layout"
              :key="item.i"
              :x="item.x"
              :y="item.y"
              :w="item.w"
              :h="item.h"
              :i="item.i"
              :min-w="2"
              :min-h="2"
              :max-w="12"
              :max-h="10"
              class="grid-item">

              <div class="visualization-item"
                   :class="{ 'selected': selectedVisualization?.id === item.i }"
                   @click="selectVisualization(visualizations.find(v => v.id === item.i))">

                <!-- 根据类型渲染不同的组件 -->
                <component
                  :is="getComponentByType(visualizations.find(v => v.id === item.i)?.type)"
                  v-if="visualizations.find(v => v.id === item.i)"
                  :title="visualizations.find(v => v.id === item.i).title"
                  :data="getVisualizationData(visualizations.find(v => v.id === item.i))"
                  :config="visualizations.find(v => v.id === item.i).config"
                  @edit="editVisualization(visualizations.find(v => v.id === item.i))" />

                <!-- 控制按钮 -->
                <div v-if="selectedVisualization?.id === item.i" class="grid-controls">
                  <el-button size="small" circle @click.stop="duplicateVisualization(visualizations.find(v => v.id === item.i))">
                    <el-icon><CopyDocument /></el-icon>
                  </el-button>
                  <el-button size="small" circle type="danger" @click.stop="removeVisualization(item.i)">
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
              </div>
            </GridItem>
          </GridLayout>




          <!-- 空状态提示 -->
          <div v-if="!visualizations.length" class="empty-state">
            <el-icon size="48" color="#c0c4cc"><DocumentAdd /></el-icon>
            <p>拖拽字段到此处开始创建可视化</p>
            <div class="layout-tips">
              <p><strong>提示：</strong></p>
              <p>• 使用网格布局可以更好地对齐组件</p>
              <p>• 按住Ctrl键拖拽可以精确定位</p>
              <p>• 使用自动排列功能快速整理布局</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧面板 -->
      <div class="right-panel">
        <div class="panel-tabs">
          <el-tabs type="border-card">
            <el-tab-pane label="可视化">
              <div class="visualization-types">
                <div class="viz-type" @click="addVisualization('table')">
                  <el-icon size="24"><Grid /></el-icon>
                  <span>表格</span>
                </div>
                <div class="viz-type" @click="addVisualization('bar')">
                  <el-icon size="24"><Histogram /></el-icon>
                  <span>柱状图</span>
                </div>
                <div class="viz-type" @click="addVisualization('line')">
                  <el-icon size="24"><TrendCharts /></el-icon>
                  <span>折线图</span>
                </div>
                <div class="viz-type" @click="addVisualization('pie')">
                  <el-icon size="24"><PieChartIcon /></el-icon>
                  <span>饼图</span>
                </div>
              </div>
            </el-tab-pane>
            <el-tab-pane label="属性">
              <div v-if="selectedVisualization" class="properties-panel">
                <h4>{{ selectedVisualization.title }}</h4>
                <el-form label-width="80px" size="small">
                  <el-form-item label="标题">
                    <el-input v-model="selectedVisualization.title" @change="updateVisualization" />
                  </el-form-item>
                  <el-form-item label="宽度">
                    <el-input-number
                      v-model="selectedVisualization.size.width"
                      :min="200"
                      :max="1200"
                      @change="updateVisualization" />
                  </el-form-item>
                  <el-form-item label="高度">
                    <el-input-number
                      v-model="selectedVisualization.size.height"
                      :min="150"
                      :max="800"
                      @change="updateVisualization" />
                  </el-form-item>

                  <!-- 网格信息 -->
                  <div v-if="layoutMode === 'grid' && selectedVisualization.gridArea" class="grid-area-info">
                    <el-divider>网格位置</el-divider>
                    <p><strong>Grid Area:</strong> {{ selectedVisualization.gridArea.cssValue }}</p>
                    <p><strong>列:</strong> {{ selectedVisualization.gridArea.columnStart }} - {{ selectedVisualization.gridArea.columnEnd }}</p>
                    <p><strong>行:</strong> {{ selectedVisualization.gridArea.rowStart }} - {{ selectedVisualization.gridArea.rowEnd }}</p>
                  </div>
                </el-form>
              </div>
              <div v-else class="no-selection">
                <p>请选择一个可视化组件</p>
              </div>
            </el-tab-pane>

            <el-tab-pane label="网格布局">
              <div class="grid-layout-panel">
                <div class="grid-info">
                  <h4>Vue3 Grid Layout 设置</h4>
                  <p><strong>列数:</strong> {{ colNum }}</p>
                  <p><strong>行高:</strong> {{ rowHeight }}px</p>
                  <p><strong>间距:</strong> {{ margin[0] }}px × {{ margin[1] }}px</p>
                  <p><strong>组件数:</strong> {{ visualizations.length }}</p>

                  <el-divider>布局设置</el-divider>
                  <el-form label-width="80px" size="small">
                    <el-form-item label="列数">
                      <el-input-number v-model="colNum" :min="6" :max="24" />
                    </el-form-item>
                    <el-form-item label="行高">
                      <el-input-number v-model="rowHeight" :min="30" :max="120" />
                    </el-form-item>
                    <el-form-item label="水平间距">
                      <el-input-number v-model="margin[0]" :min="0" :max="50" />
                    </el-form-item>
                    <el-form-item label="垂直间距">
                      <el-input-number v-model="margin[1]" :min="0" :max="50" />
                    </el-form-item>
                    <el-form-item label="可拖拽">
                      <el-switch v-model="isDraggable" />
                    </el-form-item>
                    <el-form-item label="可调整大小">
                      <el-switch v-model="isResizable" />
                    </el-form-item>
                    <el-form-item label="垂直压缩">
                      <el-switch v-model="verticalCompact" />
                    </el-form-item>
                  </el-form>

                  <el-divider>操作</el-divider>
                  <el-button
                    size="small"
                    type="primary"
                    @click="initializeLayout"
                    :disabled="!visualizations.length">
                    重新初始化布局
                  </el-button>
                </div>

                <!-- 布局信息 -->
                <div v-if="layout.length" class="layout-info">
                  <el-divider>当前布局</el-divider>
                  <div v-for="item in layout" :key="item.i" class="layout-item">
                    <p><strong>{{ visualizations.find(v => v.id === item.i)?.title }}</strong></p>
                    <p>位置: ({{ item.x }}, {{ item.y }}) 大小: {{ item.w }}×{{ item.h }}</p>
                  </div>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </div>

    <!-- 对话框 -->
    <DataImport v-model="showImportDialog" />
    <DataExport v-model="showExportDialog" />
    <ReportManager v-model="showReportManager" />

    <!-- Flex拖拽预览 -->
    <div v-if="dragPreview"
         class="drag-preview"
         :style="{
           position: 'fixed',
           left: dragPreview.x + 'px',
           top: dragPreview.y + 'px',
           width: dragPreview.width + 'px',
           height: dragPreview.height + 'px',
           background: '#fff',
           border: '2px solid #409EFF',
           borderRadius: '8px',
           boxShadow: '0 8px 24px rgba(0,0,0,0.2)',
           zIndex: 10000,
           pointerEvents: 'none',
           opacity: 0.9,
           transform: 'rotate(3deg)'
         }">
      <div style="padding: 16px; text-align: center; color: #409EFF; font-weight: 500;">
        {{ dragPreview.title }}
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { useTableStore } from '../stores/tableStore'
import FieldPanel from '../components/FieldPanel.vue'
import TableDesigner from '../components/TableDesigner.vue'
import BarChart from '../components/ChartComponents/BarChart.vue'
import LineChart from '../components/ChartComponents/LineChart.vue'
import PieChart from '../components/ChartComponents/PieChart.vue'
import FilterPanel from '../components/FilterPanel.vue'
import ThemeSelector from '../components/ThemeSelector.vue'
import DataImport from '../components/DataImport.vue'
import DataExport from '../components/DataExport.vue'
import ReportManager from '../components/ReportManager.vue'
// 导入 vue3-grid-layout
import { GridLayout, GridItem } from 'vue3-grid-layout'
import {
  DocumentAdd,
  Grid,
  Histogram,
  TrendCharts,
  PieChart as PieChartIcon,
  Delete,
  Upload,
  Download,
  Folder,
  Crop,
  Operation,
  Position,
  Rank,
  CopyDocument,
  Edit,
  Connection
} from '@element-plus/icons-vue'

// 使用store和路由
const router = useRouter()
const tableStore = useTableStore()

// 基础响应式数据
const activeTab = ref('fields')
const showImportDialog = ref(false)
const showExportDialog = ref(false)
const showReportManager = ref(false)

// Vue3 Grid Layout 配置
const layout = ref([]) // 网格布局数据
const colNum = ref(12) // 列数
const rowHeight = ref(60) // 行高
const isDraggable = ref(true) // 是否可拖拽
const isResizable = ref(true) // 是否可调整大小
const verticalCompact = ref(true) // 垂直压缩
const margin = ref([10, 10]) // 边距 [x, y]
const useCssTransforms = ref(true) // 使用CSS变换

// 兼容旧代码的必要变量（模板中仍在使用）
const layoutMode = ref('grid') // 布局模式，固定为grid
const showGrid = ref(false) // 显示网格背景
const snapToGrid = ref(false) // 网格吸附
const autoGenerateGrid = ref(false) // 自动生成网格
const isDragging = ref(false) // 拖拽状态
const dragData = ref(null) // 拖拽数据
const dragPosition = ref({ x: 0, y: 0 }) // 拖拽位置

// 计算属性
const visualizations = computed(() => tableStore.reportConfig.visualizations)
const selectedVisualization = computed(() => tableStore.selectedVisualization)
const dimensionFields = computed(() => tableStore.dimensionFields)
const measureFields = computed(() => tableStore.measureFields)

// Vue3 Grid Layout 容器样式
const gridContainerStyle = computed(() => ({
  height: '100%',
  minHeight: '600px',
  padding: '10px',
  background: '#fafafa',
  width: '100%'
}))

// 兼容旧代码的计算属性（模板中仍在使用）
const canvasStyle = computed(() => ({
  position: 'relative',
  height: '100%',
  minHeight: '600px'
}))

const gridBackgroundStyle = computed(() => ({
  backgroundImage: `
    linear-gradient(to right, #e0e0e0 1px, transparent 1px),
    linear-gradient(to bottom, #e0e0e0 1px, transparent 1px)
  `,
  backgroundSize: '20px 20px'
}))

// Vue3 Grid Layout 方法
const initializeLayout = () => {
  layout.value = visualizations.value.map((viz, index) => ({
    i: viz.id,
    x: (index % 4) * 3, // 每行4个，每个占3列
    y: Math.floor(index / 4) * 4, // 每个占4行
    w: 3, // 宽度3列
    h: 4, // 高度4行
    minW: 2,
    minH: 2,
    maxW: 12,
    maxH: 10
  }))
}

const onLayoutUpdated = (newLayout) => {
  layout.value = newLayout

  // 更新可视化组件的布局信息
  newLayout.forEach(item => {
    const viz = visualizations.value.find(v => v.id === item.i)
    if (viz) {
      viz.gridLayout = {
        x: item.x,
        y: item.y,
        w: item.w,
        h: item.h
      }
      tableStore.updateVisualization(viz.id, viz)
    }
  })
}

const addGridItem = (viz) => {
  if (!viz || !viz.id) return null

  // 为新组件找到合适的位置
  const newItem = {
    i: viz.id,
    x: 0,
    y: 0,
    w: 3,
    h: 4,
    minW: 2,
    minH: 2,
    maxW: 12,
    maxH: 10
  }

  // 找到第一个可用位置
  let placed = false
  for (let y = 0; y < 100 && !placed; y++) {
    for (let x = 0; x <= colNum.value - newItem.w && !placed; x++) {
      if (!isPositionOccupied(x, y, newItem.w, newItem.h)) {
        newItem.x = x
        newItem.y = y
        placed = true
      }
    }
  }

  layout.value.push(newItem)
  return newItem
}

const isPositionOccupied = (x, y, w, h) => {
  return layout.value.some(item => {
    return !(
      x >= item.x + item.w ||
      x + w <= item.x ||
      y >= item.y + item.h ||
      y + h <= item.y
    )
  })
}

const removeGridItem = (itemId) => {
  layout.value = layout.value.filter(item => item.i !== itemId)
}

// 根据类型获取组件
const getComponentByType = (type) => {
  const componentMap = {
    'table': TableDesigner,
    'bar': BarChart,
    'line': LineChart,
    'pie': PieChart
  }
  return componentMap[type] || 'div'
}

// 监听可视化组件变化，自动更新网格布局
watch(visualizations, (newViz) => {
  // 检查是否有新组件需要添加到网格
  newViz.forEach(viz => {
    if (!layout.value.find(item => item.i === viz.id)) {
      addGridItem(viz)
    }
  })

  // 移除已删除的组件
  layout.value = layout.value.filter(item =>
    newViz.find(viz => viz.id === item.i)
  )
}, { deep: true })

const duplicateVisualization = (viz) => {
  const newViz = {
    ...viz,
    id: Date.now().toString(),
    title: `${viz.title} - 副本`
  }

  const newVisualization = tableStore.addVisualization(newViz)
  addGridItem(newVisualization)
  tableStore.selectVisualization(newVisualization)
}

// 兼容旧代码的方法（在拖拽逻辑中使用）
const snapToGridPosition = (x, y) => {
  const gridSize = 20
  return {
    x: Math.round(x / gridSize) * gridSize,
    y: Math.round(y / gridSize) * gridSize
  }
}

const generateGridLayout = () => {
  // vue3-grid-layout 不需要手动生成布局，保留空实现避免错误
}

// 基础方法
const addVisualization = (type) => {
  const visualization = {
    type,
    title: `新建${getTypeLabel(type)}`,
    config: getDefaultConfig(type),
    data: []
  }

  const newViz = tableStore.addVisualization(visualization)

  // 添加到网格布局
  addGridItem(newViz)

  tableStore.selectVisualization(newViz)
}

const getTypeLabel = (type) => {
  const labels = {
    table: '表格',
    bar: '柱状图',
    line: '折线图',
    pie: '饼图'
  }
  return labels[type] || type
}

const getDefaultConfig = (type) => {
  switch (type) {
    case 'table':
      return { columns: [] }
    case 'bar':
    case 'line':
      return { xField: '', yField: '', color: '#409EFF' }
    case 'pie':
      return { labelField: '', valueField: '', colors: ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399'] }
    default:
      return {}
  }
}

const selectVisualization = (viz) => {
  tableStore.selectVisualization(viz)
}

const updateVisualization = () => {
  if (selectedVisualization.value) {
    tableStore.updateVisualization(selectedVisualization.value.id, selectedVisualization.value)
  }
}

const removeVisualization = (id) => {
  // 从网格布局中移除
  removeGridItem(id)

  tableStore.removeVisualization(id)
}

const getVisualizationData = (viz) => {
  return tableStore.getFilteredData()
}

const getVisualizationStyle = (viz) => {
  const baseStyle = {
    border: selectedVisualization.value?.id === viz.id ? '2px solid #409EFF' : '1px solid #ddd',
    borderRadius: '8px',
    background: '#fff',
    boxShadow: viz.isDragging ? '0 8px 24px rgba(0,0,0,0.15)' : '0 2px 8px rgba(0,0,0,0.1)',
    cursor: layoutMode.value === 'grid' ? 'grab' : 'move',
    zIndex: selectedVisualization.value?.id === viz.id ? 10 : 1,
    transition: viz.isDragging ? 'none' : 'all 0.2s ease',
    opacity: viz.isDragging ? 0.5 : 1
  }

  // 网格模式：使用Flex布局
  if (layoutMode.value === 'grid') {
    return {
      ...baseStyle,
      flex: `${viz.flexGrow || 0} ${viz.flexShrink || 1} ${viz.flexBasis || 'auto'}`,
      minHeight: '200px',
      maxHeight: '400px',
      margin: `${flexGap.value / 2}px 0`,
      order: viz.flexOrder || 0
    }
  }

  // 自由模式：使用绝对定位
  if (!viz.position || !viz.size) return baseStyle

  return {
    ...baseStyle,
    position: 'absolute',
    left: `${viz.position.x}px`,
    top: `${viz.position.y}px`,
    width: `${viz.size.width}px`,
    height: `${viz.size.height}px`
  }
}

// 拖拽功能
const startDrag = (viz, event) => {
  if (event.target.closest('.viz-controls')) return // 不拖拽控制按钮

  event.preventDefault()

  isDragging.value = true
  dragData.value = {
    viz,
    startX: event.clientX,
    startY: event.clientY,
    originalX: viz.position.x,
    originalY: viz.position.y,
    element: event.currentTarget
  }

  tableStore.selectVisualization(viz)

  // 添加拖拽样式
  dragData.value.element.classList.add('dragging')
  document.body.style.userSelect = 'none'
  document.body.style.cursor = 'grabbing'

  const handleMouseMove = (e) => {
    if (!isDragging.value || !dragData.value) return

    const deltaX = e.clientX - dragData.value.startX
    const deltaY = e.clientY - dragData.value.startY

    let newX = dragData.value.originalX + deltaX
    let newY = dragData.value.originalY + deltaY

    // 网格吸附
    if (snapToGrid.value) {
      const snapped = snapToGridPosition(newX, newY)
      newX = snapped.x
      newY = snapped.y
    }

    // 边界检测
    newX = Math.max(0, newX)
    newY = Math.max(0, newY)

    // 更新拖拽位置信息
    dragPosition.value = { x: newX, y: newY }

    // 直接更新DOM样式，避免频繁的store更新
    if (dragData.value.element) {
      const actualDeltaX = newX - dragData.value.originalX
      const actualDeltaY = newY - dragData.value.originalY
      dragData.value.element.style.transform = `translate(${actualDeltaX}px, ${actualDeltaY}px)`
    }
  }

  const handleMouseUp = (e) => {
    if (!isDragging.value || !dragData.value) return

    // 计算最终位置
    const deltaX = e.clientX - dragData.value.startX
    const deltaY = e.clientY - dragData.value.startY

    let newX = dragData.value.originalX + deltaX
    let newY = dragData.value.originalY + deltaY

    // 网格吸附
    if (snapToGrid.value) {
      const snapped = snapToGridPosition(newX, newY)
      newX = snapped.x
      newY = snapped.y
    }

    // 边界检测
    newX = Math.max(0, newX)
    newY = Math.max(0, newY)

    // 更新可视化组件位置
    dragData.value.viz.position.x = newX
    dragData.value.viz.position.y = newY
    tableStore.updateVisualization(dragData.value.viz.id, dragData.value.viz)

    // 如果启用了自动生成网格，重新生成网格布局
    if (autoGenerateGrid.value) {
      generateGridLayout()
    }

    // 清理拖拽状态
    cleanup()
  }

 
  document.addEventListener('mousemove', handleMouseMove)
  document.addEventListener('mouseup', handleMouseUp)
}

// 拖拽处理
const onDrop = (event) => {
  event.preventDefault()

  try {
    const fieldData = JSON.parse(event.dataTransfer.getData('application/json'))

    // 根据字段类型自动创建合适的可视化
    let vizType = 'table'
    if (fieldData.category === '度量值') {
      vizType = 'bar'
    }

    const rect = event.currentTarget.getBoundingClientRect()
    const x = event.clientX - rect.left
    const y = event.clientY - rect.top

    const visualization = {
      type: vizType,
      title: `${fieldData.name}分析`,
      config: vizType === 'table'
        ? { columns: [fieldData.id] }
        : { xField: '', yField: fieldData.id, color: '#409EFF' },
      data: []
    }

    const newViz = tableStore.addVisualization(visualization)
    newViz.position = { x: Math.max(0, x - 200), y: Math.max(0, y - 150) }

    tableStore.selectVisualization(newViz)
  } catch (error) {
    console.error('拖拽处理失败:', error)
  }
}

const editVisualization = (viz) => {
  tableStore.selectVisualization(viz)
}

const saveReport = async () => {
  try {
    // 动态导入报表工具函数
    const { saveReport: saveReportUtil } = await import('../utils/reportUtils')
    const { ElMessage } = await import('element-plus')

    const reportId = saveReportUtil(tableStore.reportConfig, tableStore.reportConfig.title)
    ElMessage.success('报表保存成功')
    console.log('报表已保存:', reportId)
  } catch (error) {
    console.error('保存报表失败:', error)
    const { ElMessage } = await import('element-plus')
    ElMessage.error('保存报表失败')
  }
}

const previewReport = () => {
  console.log('预览报表')
  // 这里可以实现预览逻辑
}

const goToDataModel = () => {
  router.push('/data-model')
}

// 组件挂载时初始化布局
onMounted(() => {
  // 如果有现有的可视化组件，初始化网格布局
  if (visualizations.value.length > 0) {
    initializeLayout()
  }
})

// 组件卸载前清理
onBeforeUnmount(() => {
  // 清空布局数据
  layout.value = []

  // 清理拖拽状态
  isDragging.value = false
  dragData.value = null
})
</script>

<style scoped>
.powerbi-designer {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  background: #fff;
  border-bottom: 1px solid #e0e0e0;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.toolbar-label {
  font-size: 12px;
  color: #666;
  margin: 0 8px 0 16px;
}

.toolbar-left h2 {
  margin: 0;
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

.toolbar-right {
  display: flex;
  gap: 8px;
}

.main-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.left-panel {
  width: 280px;
  background: #fff;
  border-right: 1px solid #e0e0e0;
  overflow-y: auto;
}

.design-area {
  flex: 1;
  position: relative;
  overflow: auto;
}

.design-canvas {
  position: relative;
  width: 100%;
  height: 100%;
  min-height: 600px;
  background: #ffffff;
  transition: background-color 0.3s ease;
}

.design-canvas.grid-mode {
  background: #fafafa;
}

.design-canvas.show-grid {
  background-image:
    linear-gradient(to right, #e0e0e0 1px, transparent 1px),
    linear-gradient(to bottom, #e0e0e0 1px, transparent 1px);
  background-size: 20px 20px;
}

/* 移除了限制性的网格样式，允许组件自由重叠 */

.grid-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  opacity: 0.5;
}

.visualization-item {
  position: absolute;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  cursor: move;
  transition: all 0.2s ease;
  overflow: hidden;
}

.visualization-item:hover {
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}

.visualization-item.selected {
  border: 2px solid #409EFF;
  box-shadow: 0 0 0 4px rgba(64, 158, 255, 0.2);
}

.visualization-item.dragging {
  opacity: 0.8;
  transform: rotate(2deg);
  z-index: 1000;
}

.visualization-item.grid-item {
  transition: all 0.3s ease;
}

.drag-handle {
  position: absolute;
  top: 4px;
  left: 4px;
  width: 20px;
  height: 20px;
  background: #409EFF;
  color: white;
  border-radius: 3px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: grab;
  font-size: 12px;
  z-index: 10;
}

.drag-handle:active {
  cursor: grabbing;
}

.resize-handles {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
}

.resize-handle {
  position: absolute;
  background: #409EFF;
  border: 1px solid #fff;
  border-radius: 2px;
  pointer-events: all;
  z-index: 20;
}

/* 角落手柄 */
.resize-handle.nw,
.resize-handle.ne,
.resize-handle.sw,
.resize-handle.se {
  width: 8px;
  height: 8px;
}

.resize-handle.nw {
  top: -4px;
  left: -4px;
  cursor: nw-resize;
}

.resize-handle.ne {
  top: -4px;
  right: -4px;
  cursor: ne-resize;
}

.resize-handle.sw {
  bottom: -4px;
  left: -4px;
  cursor: sw-resize;
}

.resize-handle.se {
  bottom: -4px;
  right: -4px;
  cursor: se-resize;
}

/* 边缘手柄 */
.resize-handle.n,
.resize-handle.s {
  width: 20px;
  height: 4px;
  left: 50%;
  transform: translateX(-50%);
}

.resize-handle.w,
.resize-handle.e {
  width: 4px;
  height: 20px;
  top: 50%;
  transform: translateY(-50%);
}

.resize-handle.n {
  top: -2px;
  cursor: n-resize;
}

.resize-handle.s {
  bottom: -2px;
  cursor: s-resize;
}

.resize-handle.w {
  left: -2px;
  cursor: w-resize;
}

.resize-handle.e {
  right: -2px;
  cursor: e-resize;
}

.resize-handle:hover {
  background: #1890ff;
  transform: scale(1.2);
}

.viz-controls {
  position: absolute;
  top: 4px;
  right: 4px;
  display: flex;
  gap: 4px;
  z-index: 10;
}

.grid-info {
  position: absolute;
  bottom: 4px;
  left: 4px;
  background: rgba(0,0,0,0.7);
  color: white;
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 10px;
  z-index: 10;
}

.right-panel {
  width: 300px;
  background: #fff;
  border-left: 1px solid #e0e0e0;
  overflow-y: auto;
}

.panel-tabs {
  height: 100%;
}

.visualization-types {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  padding: 16px;
}

.viz-type {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 16px;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
  background: #fff;
}

.viz-type:hover {
  border-color: #409EFF;
  background: #f0f8ff;
  transform: translateY(-2px);
}

.viz-type span {
  font-size: 12px;
  color: #666;
}

.properties-panel {
  padding: 16px;
}

.properties-panel h4 {
  margin: 0 0 16px 0;
  color: #333;
}

.no-selection {
  padding: 16px;
  text-align: center;
  color: #999;
}

.empty-state {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  color: #999;
}

.empty-state p {
  margin: 16px 0;
  font-size: 16px;
}

.layout-tips {
  margin-top: 24px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
  text-align: left;
  max-width: 300px;
}

.layout-tips p {
  margin: 8px 0;
  font-size: 14px;
  color: #666;
}

.layout-tips strong {
  color: #333;
}

/* 网格布局面板样式 */
.grid-layout-panel {
  padding: 16px;
}

.grid-info h4 {
  margin: 0 0 12px 0;
  color: #333;
}

.grid-info p {
  margin: 8px 0;
  font-size: 14px;
  color: #666;
}

.grid-definition {
  background: #f5f5f5;
  padding: 8px 12px;
  border-radius: 4px;
  margin: 8px 0;
  font-family: 'Courier New', monospace;
  font-size: 12px;
}

.grid-definition code {
  color: #e74c3c;
  font-weight: 500;
}

.empty-text {
  color: #999;
  font-style: italic;
}

.css-preview {
  margin-top: 16px;
}

.css-code {
  background: #2d3748;
  color: #e2e8f0;
  padding: 16px;
  border-radius: 6px;
  font-size: 12px;
  line-height: 1.5;
  overflow-x: auto;
  white-space: pre-wrap;
  word-break: break-all;
}

.grid-area-info {
  margin-top: 16px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
}

.grid-area-info p {
  margin: 4px 0;
  font-size: 12px;
  color: #666;
}

.grid-area-info strong {
  color: #333;
}

/* 网格位置指示器 */
.grid-position-indicator {
  position: absolute;
  top: 4px;
  left: 4px;
  background: rgba(64, 158, 255, 0.9);
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 11px;
  font-weight: 500;
  z-index: 20;
  pointer-events: none;
}

/* 网格模式下的组件样式 */
.design-canvas.grid-mode .visualization-item {
  cursor: default;
}

.design-canvas.grid-mode .visualization-item:hover {
  transform: none;
}

/* Vue3 Grid Layout 样式 */
.grid-item {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  transition: all 0.2s ease;
}

.grid-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.visualization-item {
  height: 100%;
  width: 100%;
  position: relative;
  cursor: default;
}

.visualization-item.selected {
  border-color: #409EFF;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.grid-controls {
  position: absolute;
  top: 8px;
  right: 8px;
  display: flex;
  gap: 4px;
  opacity: 0;
  transition: opacity 0.2s ease;
  z-index: 10;
}

.grid-item:hover .grid-controls,
.visualization-item.selected .grid-controls {
  opacity: 1;
}

.layout-info {
  margin-top: 16px;
}

.layout-item {
  padding: 8px;
  margin: 4px 0;
  background: #f5f7fa;
  border-radius: 4px;
  font-size: 12px;
}

/* Vue3 Grid Layout 拖拽样式 */
.vue-grid-item.vue-grid-placeholder {
  background: rgba(64, 158, 255, 0.2) !important;
  border: 2px dashed #409EFF !important;
  border-radius: 8px;
}

.vue-grid-item.vue-draggable-dragging {
  transition: none;
  z-index: 3;
  opacity: 0.8;
}

.vue-grid-item.vue-resizable-resizing {
  opacity: 0.8;
  z-index: 3;
}

.vue-grid-item > .vue-resizable-handle {
  background: #409EFF;
  opacity: 0.3;
}

.vue-grid-item:hover > .vue-resizable-handle {
  opacity: 0.8;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .left-panel {
    width: 240px;
  }

  .right-panel {
    width: 260px;
  }
}

@media (max-width: 768px) {
  .toolbar-left {
    gap: 8px;
  }

  .toolbar-left h2 {
    font-size: 16px;
  }

  .left-panel,
  .right-panel {
    width: 200px;
  }

  .visualization-types {
    grid-template-columns: 1fr;
  }
}
</style>
